from rest_framework import serializers

from users.models import CustomUser
from users.serializers import UserSerializer
from .models import Artwork, Order, Comment, Rating
import random
import string


class ArtworkSerializer(serializers.ModelSerializer):
    """
    艺术品的序列化器
    """
    artist = UserSerializer()

    class Meta:
        model = Artwork
        fields = '__all__'
        read_only_fields = ('id',)  # 只读字段


class ArtworkCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Artwork
        fields = '__all__'
        read_only_fields = ('id',)  # 只读字段


class OrderSerializer(serializers.ModelSerializer):
    buyer = UserSerializer()
    artwork = ArtworkSerializer()
    original_artist = UserSerializer()

    class Meta:
        model = Order
        fields = '__all__'
        read_only_fields = ('id',)  # 只读字段


class OrderCreateSerializer(serializers.ModelSerializer):
    order_number = serializers.SerializerMethodField()

    class Meta:
        model = Order
        fields = '__all__'
        read_only_fields = ('id', 'order_number')  # 只读字段

    def get_order_number(self, obj):
        return obj.order_number  # 返回订单对象中的订单号

    def create(self, validated_data):
        order_number = self.generate_order_number()  # 生成订单号
        validated_data['order_number'] = order_number  # 将生成的订单号添加到验证数据中
        return super().create(validated_data)

    def generate_order_number(self):
        # 生成订单号的逻辑，此处使用您之前提供的生成方法
        return ''.join(random.choices(string.digits, k=6))


class CommentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Comment
        fields = '__all__'
        read_only_fields = ['id', 'created_at']


class CommentListSerializer(serializers.ModelSerializer):
    user = UserSerializer()
    artwork = ArtworkSerializer()

    class Meta:
        model = Comment
        fields = '__all__'
        read_only_fields = ['id', 'created_at']


class RatingSerializer(serializers.ModelSerializer):
    class Meta:
        model = Rating
        fields = '__all__'
        read_only_fields = ['id', 'created_at']


class RatingListSerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = Rating
        fields = '__all__'
        read_only_fields = ['id', 'created_at']


class CommentAndRatingSerializer(serializers.Serializer):
    """
    评论和评分的序列化器
    """
    artwork = serializers.PrimaryKeyRelatedField(queryset=Artwork.objects.all())
    user = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all())

    content = serializers.CharField(required=False, allow_blank=True)
    score = serializers.IntegerField(required=False, min_value=1, max_value=5)

    def create(self, validated_data):
        artwork = validated_data.pop('artwork')
        user = validated_data.pop('user')
        content = validated_data.pop('content', None)
        score = validated_data.pop('score', None)

        comment = None
        rating = None

        if content:
            comment = Comment.objects.create(artwork=artwork, user=user, content=content)

        if score:
            rating = Rating.objects.create(artwork=artwork, user=user, score=score)

        if not comment and not rating:
            raise serializers.ValidationError("评论内容和评分都为空")
        return {'comment': comment, 'rating': rating}
